<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.3.6.1.min.js"></script>
<script src="js/tabulator.5.4.2.min.js"></script>
<script src="js/underscore.js"></script>
<script src="js/jsonform.js"></script>
<!-- <script src="js/layoutCss.js"></script>
<script src="lib/LocalString.js"></script>
<script src="lib/JiraSync.js"></script>
<script src="lib/SyncTicketForm.js"></script>
<script src="lib/User.js"></script>
<script src="action/syncTicketEnter.js"></script> -->
</head>
<body>  
<div class="aui-header-primary">
  <ul class="aui-nav">

  </ul>

</div>

<script>
// Init content box
let css = [
        "https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css"
    ];
let boxStyle = 'position: fixed; top: 0;';
    boxStyle += 'display:flex; justify-content: center; width: 100%;';
    boxStyle += 'border: 1px solid red';
let filterContainer = '<div id="grid-filter"></div>';
let gridContainer = '<div id="example-table"></div>';
let container = '<div id="grid-content" style="' + boxStyle + '">' + filterContainer + gridContainer + '</div>';

for (let idx in css) {
    jQuery('head').append('<link crossorigin="anonymous" media="all" rel="stylesheet" href="' + css[idx] + '">');
}

/**************************************
 * mapping
 **************************************/
var mapping = {
        key:"key",
        summary:"summary",
        fix_version:"fix_version",
        status:"status",
        developer:"developer",
        country_convery:"country_convery",
        ticket_action:"ticket_action",
        area_impact:"area_impact",
        code_merge:"code_merge",
        code_branch:"code_branch"
    };

var countryConveryOptions = {"Yess":"Yess", "Noo":"Noo"};
var areaImpactOptions = {"Yes":"Yes", "No":"No"};
var ticketActionOptions = {"Yes":"Yes", "No":"No"};
var codeMergeOptions = {"Yes":"Yes", "No":"No"};
var statusOptions = {"Done":"Done", "Processing":"Processing"};

var tableColumns = [
            {title:"FixVersion", field:"fix_version", sorter:"string", editor:"input"},
            {title:"Key", field:"key", sorter:"string"},
            {title:"Summary", field:"summary", sorter:"string"},
            {title:"Status", field:"status", sorter:"string", editor: "list", editorParams: {
                values: statusOptions
            }},
            {title:"Developer", field:"developer", sorter:"string"},
            {title:"Country convery", field:"country_convery", hozAlign:"center",
             editor:"list",
             editorParams:{
                 multiselect:true,
                 values:countryConveryOptions
             }
            },
            {title:"Area Impact", field:"area_impact", sorter:"date", hozAlign:"center",
             editor:"list",
             editorParams:{
                 multiselect:true,
                 autocomplete: false,
                 clearable:true,
                 values:areaImpactOptions
             }
            },
            {title:"Ticket Action", field:"ticket_action", sorter:"string", editor:"list", editorParams:{values:ticketActionOptions}},
            {title:"Code Merge", field:"code_merge", hozAlign:"center", editor:"list", editorParams:{values:codeMergeOptions}},
            {title:"Branch", field:"code_branch", hozAlign:"center", editor:"input"},
            {title:"Action", field:"self", hozAlign:"center", formatter: function(cell, formatterParams){
                return '<span>Update</span>';
            }, cellClick:function(e, cell) {
                console.log('#format', cell.getRow().getData());
                console.log(cell.getRow());
                // sync data to JIRA


            }}
        ];
/**************************************
 * Class
 **************************************/




// Init layout
jQuery(function(){
    var contentXpath = '.aui-header-primary ul.aui-nav';
    var issueKeyXpath = '#key-val';
    var syncButtonXpath = '#show-validate-tickets-button';
    var syncDiv = '<li style="display:flex;align-items: center;">';
        syncDiv += '<button id="show-validate-tickets-button" class="aui-button aui-button-primary aui-style">Show Validate Tickets</button><div id="sync-icon" class="lds-dual-ring" style="display:none;"></div>';
        syncDiv += '</li>';
    var loadingCss = '<style>';
        loadingCss += '.lds-dual-ring{display:inline-block;}.lds-dual-ring:after{content:" ";display:block;width:8px;height:8px;margin:8px;border-radius:50%;border:6px solid #cef;border-color:#cef transparent #cef transparent;animation:lds-dual-ring 1.2s linear infinite;}@keyframes lds-dual-ring{0%{transform:rotate(0deg);}100%{transform:rotate(360deg);}}';
        loadingCss += '</style>';
    var gridId = 'grid-layout';
    var gridXpath = '#' + gridId;
    var gridLayoutCss = '<style>';
        gridLayoutCss += gridXpath + '{border: 1px solid red;width: 100%;padding: 5px; position: fixed;top: 0;background-color:white;z-index:100;}';
        gridLayoutCss += `
#grid-layout .grid-layout {
display: flex;
flex-direction: column;
}
.config
{
    display: flex;
    pending: 5px;
    flex-direction: column;
    with: 98%;
}
.config .row
{
    display: flex;
    flex: 0.98;
}
.config .close
{
    display: flex;
    justify-content: end;
cursor: pointer;
font-size: 14px;
font-weight: bold;
color: red;
}
.row form, .row form > div
{
    display: flex;
    flex: 0.98;
    flex-direction: column;
}
.row fieldset
{
    display: flex;
}
.row .form-group
{
    padding: 5px;
}
    `;
        gridLayoutCss += '</style>';
    var gridContainer = '<div id="' + gridId + '" style="display:none;"><div class="' + gridId + '">';
        gridContainer += '<div class="config">';
        gridContainer += '<div class="row close"><span>Close</span></div>';
        gridContainer += '<div class="row"><form></form></div>';
        gridContainer += '</div>';
        gridContainer += '<div id="table-list">Table</div>';
        gridContainer += '</div></div>';

    // add button
    jQuery('head').append(loadingCss);
    jQuery('head').append(gridLayoutCss);
    // @TODO
    //jQuery(contentXpath).append(syncDiv);
    jQuery('body').append(gridContainer);
    /*************************************
     * Init Filter form
     *************************************/
    jQuery(gridXpath + ' .config form').jsonForm({
        schema: {
             host: {
                type: 'string',
                title: 'Host',
                required: true,
                default: localStorage.getItem('host')
            },
            token: {
                type: 'string',
                title: 'API Token',
                required: true,
                default: localStorage.getItem('token')
            },
            jql: {
                type: 'string',
                title: 'JQL',
                required: true,
                default: localStorage.getItem('jql')
            }
        },
        "form": [
            {
                "type": "fieldset",
                "title": "Config",
                "expandable": false,
                "items": [
                    "host",
                    "token"
                ]
            },
            {
                "key": "jql",
                "type": "textarea"
            },
            {
                "type": "actions",
                "items": [
                    {
                        "type": "submit",
                        "title": "Search"
                    },
                    {
                        "type": "button",
                        "title": "Update"
                    }
                ]
            }
        ],
        onSubmit: function (errors, values) {
            console.log('#errors', errors);
            if (errors) {
                $('#res').html('<p>I beg your pardon?</p>');
            }
            else {
                console.log("#form submit");
            }

            // set data to localstrong
            localStorage.setItem('host', jQuery('#jsonform-1-elt-host').val());
            localStorage.setItem('token', jQuery('#jsonform-1-elt-token').val());
            localStorage.setItem('jql', jQuery('#jsonform-1-elt-jql').val());


            let baseUrl = localStorage.getItem('host');
            let options = {
                method: 'get',
                headers: {
                    'Content-Type':'application/json',
                    'Authorization':'Bearer ' + localStorage.getItem('token')
                }
            };
            table.setData(baseUrl + "/rest/api/2/search?jql=" + localStorage.getItem('jql'), {}, options);

        }
    });
    /************************************
     * Init Table
     ************************************/
    var table = new Tabulator("#table-list", {
        height:"311px",
        layout:"fitColumns",
        placeholder:"No Data Set",
        columns:tableColumns,
        rowFormatter: function(row){
            let rowData = row.getData();
        },
        ajaxResponse:function(url, params, resp){
            console.log('#table resp', resp);
            //url - the URL of the request
            //params - the parameters passed with the request
            //response - the JSON object returned in the body of the response.
            // create table list
            let rows = [];
            if (resp.total) {
                let issues = resp.issues;
                for (idx in issues) {
                    // need add mapping
                    // @TODO
                    /*************************************/

                    console.log('#resp[idx]', issues[idx]);
                    let issue = issues[idx];
                    /**
                    let row = {
                        key: issue.key,
                        summary: issue.fields.summary,
                        priority: issue.fields.priority.name,
                        fix_version: issue.fields.fixVersions !== null ? issue.fields.fixVersions[0].name : '',
                        status: issue.fields.status.name,
                        //developer: issue.fields.assignee.name,
                        developer: issue.fields.customfield_13700 !== null ? issue.fields.customfield_13700[0].name : '', // @todo array
                        country_convery: issue.fields.customfield_13423 !== null ? issue.fields.customfield_13423[0].value : '', // @todo array
                        region: issue.fields.customfield_14800 !== null ? issue.fields.customfield_14800[0].value : '', // @todo array issue.fields.customfield_14800 is null
                        ticket_action: issue.fields.customfield_13431 !== null ? issue.fields.customfield_13431.value : '',
                        area_impact: issue.fields.customfield_15300 !== null ? issue.fields.customfield_15300.value : '',
                        code_merge: issue.fields.customfield_15820 !== null ? issue.fields.customfield_15820.value : '',
                        code_branch: issue.fields.customfield_15819,
                        self: issue.self
                    };
                    //*/
                    let row = {
                        key: issue.key,
                        summary: issue.fields.summary,
                        priority: issue.fields.priority.name,
                        fix_version: issue.fields.fixVersions !== null ? issue.fields.fixVersions[0].name : '',
                        status: issue.fields.status.name,
                        //developer: issue.fields.assignee.name,

                        self: issue.self
                    };

                    rows.push(row);
                }
            }
console.log('#rows', rows);
            return rows; //return the tableData property of a response json object
        }
    });

    // @todo temp add to body
    jQuery('body').append('<div style="position: fixed; top:0; z-index:100;left:75%;"><ul id="test">' + syncDiv + '</ul></div>');


    // band click event, show layout
    jQuery(syncButtonXpath).on('click', function(){
        // show table
        jQuery(gridXpath).show();
        // Init Table
        //jQuery(gridXpath + ' #table-list').html('');
    });

    // Close
    jQuery('.config .close').on('click', function(){
        jQuery(gridXpath).hide();
    });
});
</script>
</body>
</html>